#include "main.h"
#include "crow.h"
using namespace std;

int cmpHeat(LocationStruct a, LocationStruct b) {
    return a.heat > b.heat;
}

int cmpRating(LocationStruct a, LocationStruct b) {
    return a.rating > b.rating;
}

// 查询地点列表接口实现
crow::json::wvalue locationEntry(const char* keyword, int sortby, int type, int limit, int offset) {
    crow::json::wvalue root;

    vector<LocationStruct>* sourceTable = nullptr;
    if (type == 1)
        sourceTable = &LocationTable_Spot;
    else if (type == 2)
        sourceTable = &LocationTable_Campus;
    else
        sourceTable = &LocationTable;

    vector<LocationStruct> data = *sourceTable; // 复制数据
    if (keyword != nullptr && strlen(keyword) > 0) {
        string keywordLower = keyword;
        transform(keywordLower.begin(), keywordLower.end(), keywordLower.begin(), ::tolower);
        vector<LocationStruct> filtered;
        for (auto& item : data) {
            string nameLower = item.name;
            transform(nameLower.begin(), nameLower.end(), nameLower.begin(), ::tolower);
            if (nameLower.find(keywordLower) != string::npos) {
                filtered.push_back(item);
            }
        }
        data = move(filtered);
    }

    if (sortby == 1)
        sort(data.begin(), data.end(), cmpHeat);
    else if (sortby == 2)
        sort(data.begin(), data.end(), cmpRating);

    int total = data.size();
    int count = min(limit, max(total - offset, 0));

    crow::json::wvalue data_array = crow::json::wvalue::list();
    for (int i = 0; i < count; ++i) {
        int idx = i + offset;
        if (idx >= total) break;
        data_array[i]["id"] = data[idx].id;
        data_array[i]["name"] = data[idx].name;
        data_array[i]["type"] = data[idx].type;
        data_array[i]["heat"] = data[idx].heat;
        data_array[i]["rating"] = data[idx].rating;
    }

    root["success"] = true;
    root["count"] = count;
    root["data"] = move(data_array);

    return root;
}
